package top.healthylife.gateway.platform.td.api.api.creditbodyguard;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import top.healthylife.basics.utils.exception.BusinessException;
import top.healthylife.gateway.core.service.ParentFace;
import top.healthylife.gateway.dto.annotation.ApiServiceExplain;
import top.healthylife.gateway.platform.td.api.utils.TdUtils;
import top.healthylife.gateway.platform.td.dto.creditbodyguard.precreditauditscore.req.TdReqPreCreditAuditScoreDto;
import top.healthylife.gateway.platform.td.dto.creditbodyguard.precreditauditscore.res.*;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * @author : GaoZeXi
 * @date 2021/7/28 9:48
 */
@Slf4j
@Service
@ApiServiceExplain(price = 20, apiName = "贷前综合分", info = "信贷保镖紧密围绕客户的业务和风控需求，为银行信用卡、现金贷、消费金融、汽车金融等各行各业的客户提供全生命周期的一站式定制服务，并采用项目模式提供咨询、数据、产品、运营等协同服务。全力协助客户在保证业务质量的同时提高业务效率，规避业务风险，最终实现盈利目标。")
public class TdBusinessFlowPreCreditAuditScoreApi implements ParentFace<TdReqPreCreditAuditScoreDto, TdResPreCreditAuditScoreDto> {
    static final String URL = "/bodyguard/apply/v5";
    static final String METHOD = "POST";
    static final String BIZ_CODE = "jck_jck_loanzhf";
    static Map<String, Class<?>> types = new HashMap<>();

    static {
        types.put("suspected_team", SuspectedTeam.class);
        types.put("grey_list", GreyList.class);
        types.put("fuzzy_black_list", FuzzyBlackList.class);
        types.put("frequency_detail", FrequencyDetail.class);
        types.put("cross_frequency_detail", CrossFrequencyDetail.class);
        types.put("cross_event_detail", CrossEventDetail.class);
        types.put("discredit_count", DiscreditCount.class);
        types.put("custom_list", CustomList.class);
        types.put("platform_detail", PlatformDetail.class);
        types.put("black_list", BlackList.class);
        types.put("device_status_abnormal", DeviceStatusAbnormal.class);
        types.put("fp_exception", FpException.class);
        types.put("function_kit", FunctionKit.class);
        types.put("creditList_index_detail", CreditListIndexDetail.class);
        types.put("four_calculate", FourCalculate.class);
        types.put("assoc_risk_score", AssocRiskScore.class);
        types.put("indicatrix_result", IndicatrixResult.class);
    }

    @Override
    public TdResPreCreditAuditScoreDto execute(TdReqPreCreditAuditScoreDto t) throws Exception {
        //fixme 同盾贷前综合分,入参-获客渠道 修改默认值为1  2021-8-20 20:14:44  业务方要求:朱老师
        t.setCustomerChannel("1");
        JSONObject jsonObject = TdUtils.tongDunHttpRequest(t, URL, METHOD, BIZ_CODE);
        TdResPreCreditAuditScoreDto tdResPreCreditAuditScoreDto = jsonObject.toJavaObject(TdResPreCreditAuditScoreDto.class);
        JSONObject antifraud = jsonObject.getJSONObject(TdUtils.RESULT_DESC).getJSONObject("ANTIFRAUD");
        JSONArray jsonArray = antifraud.getJSONArray("risk_items");
        if(ObjectUtil.isNotEmpty(jsonArray)){
            List<List<RiskDetail>> riskDetailsList = jsonArray.stream().map(e -> {
                JSONObject e1 = (JSONObject) e;
                JSONArray jsonArray1 = e1.getJSONArray("risk_detail");
                List<RiskDetail> riskDetails = new ArrayList<>();
                if(ObjectUtil.isEmpty(jsonArray1)){
                    return riskDetails;
                }
                jsonArray1.forEach(details -> {
                    JSONObject details1 = (JSONObject) details;
                    String type = details1.getString("type");
                    if (!types.containsKey(type)) {
                        throw new BusinessException("同盾[贷前综合分]数据结构解析异常:不期望的type值:{}", type);
                    }
                    Class<?> aClass = types.get(type);
                    RiskDetail riskDetail = details1.toJavaObject((Type) aClass);
                    riskDetails.add(riskDetail);
                });
                return riskDetails;
            }).collect(Collectors.toList());
            List<RiskItems> riskItems = tdResPreCreditAuditScoreDto.getResultDesc().getAntifraud().getRiskItems();
            for (int i = 0; i < riskItems.size(); i++) {
                riskItems.get(i).setRiskDetail(riskDetailsList.get(i));
            }
        }
        return tdResPreCreditAuditScoreDto;
    }
}
